package com.chen.pfm.slice;

import com.chen.pfm.ResourceTable;
import com.chen.pfm.entity.Account;
import com.chen.pfm.entity.Classify;
import com.chen.pfm.entity.ResultVo;
import com.chen.pfm.entity.StatisticsInfo;
import com.chen.pfm.provider.ClassifyProvider;
import com.chen.pfm.utils.*;

import com.google.gson.Gson;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.CommonDialog;
import ohos.agp.window.dialog.IDialog;
import ohos.agp.window.dialog.ListDialog;
import ohos.app.AbilityContext;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.*;

import static ohos.agp.components.ComponentContainer.LayoutConfig.MATCH_CONTENT;
import static ohos.agp.components.ComponentContainer.LayoutConfig.MATCH_PARENT;

public class KeepAccountsAbilitySlice extends AbilitySlice implements RadioContainer.CheckedStateChangedListener {
    static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0x00201, "KeepAccountsAbilitySlice");
    //日期和时间,账单分类
    private Text dateText, dateTimeText, classText, remarkText;
    //按钮，记账保持按钮，返回按钮，取消
    private Button saveRecordBtn, goBackBtn, keepaccounts_cancel;
    //记账的金额，支付事项，备注
    private TextField moneyTextfield;
    //单选框容器
    private RadioContainer accountsTypeRadiocontainer;
    //账单类型
    private int accountsType = 0; //0表示支出，1表示收入,2资产
    //日期  年-月-日，时-分-秒
    private int dateYear, dateMonth, dateDay, hours, mimute, second;
    List<Classify> classifies_expenditure;//花费
    List<Classify> classifies_income;//收入
    List<Classify> classifies_property;//资产
    ListContainer listContainer;//列表容器
    List<Classify> openclassify;
    ClassifyProvider classifyProvider;//数据适配器
    Classify item;//选中的分类信息
    boolean iskeepaccount = false;
    DirectionalLayout layout_aremark;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_keep_accounts);

        //日期
        dateText = (Text) findComponentById(ResourceTable.Id_date_text);
        dateText.setClickedListener(keepAccountsClickedListener);

        //时间
        dateTimeText = (Text) findComponentById(ResourceTable.Id_date_time_text);
        dateTimeText.setClickedListener(keepAccountsClickedListener);


        //右上角保存按钮
        saveRecordBtn = (Button) findComponentById(ResourceTable.Id_keepaccounts_save);
        saveRecordBtn.setClickedListener(keepAccountsClickedListener);

        //左上角返回按钮
        goBackBtn = (Button) findComponentById(ResourceTable.Id_goback_btn);
        goBackBtn.setClickedListener(keepAccountsClickedListener);

        //记账的金额
        moneyTextfield = (TextField) findComponentById(ResourceTable.Id_money_textfield);
        reloadColorData();
        //分类
        classText = (Text) findComponentById(ResourceTable.Id_class_text);
        classText.setClickedListener(keepAccountsClickedListener);
        //备注
        remarkText = (Text) findComponentById(ResourceTable.Id_remark_textfield);
        layout_aremark = (DirectionalLayout) findComponentById(ResourceTable.Id_layout_aremark);
        layout_aremark.setClickedListener(component -> getInputFromTextTextField(this, "账单备注", "请输入账单备注", component));

        //账单类型
        accountsTypeRadiocontainer = (RadioContainer) findComponentById(ResourceTable.Id_in_ex_radiocontainer);
        accountsTypeRadiocontainer.setMarkChangedListener(this);
        //加载数据
        try {

            classifies_expenditure = ClassifyDBUtil.queryAllClassifyByCtype1(this, 1);
            classifies_income = ClassifyDBUtil.queryAllClassifyByCtype1(this, 2);
            classifies_property = ClassifyDBUtil.queryAllClassifyByCtype1(this, 3);

        } catch (DataAbilityRemoteException e) {
            e.printStackTrace();
        }
    }

    void reloadColorData() {
        getUITaskDispatcher().asyncDispatch(() -> {
            if (accountsType == 0) {//支出
                moneyTextfield.setTextColor(new Color(Color.getIntColor("#ff383b")));
            } else if (accountsType == 1) {//收入
                moneyTextfield.setTextColor(new Color(Color.getIntColor("#FF47AB93")));
            } else {//资产
                moneyTextfield.setTextColor(new Color(Color.getIntColor("#1296db")));
            }
        });
    }


    private Component.ClickedListener keepAccountsClickedListener = new Component.ClickedListener() {
        @Override
        public void onClick(Component component) {
            int componentId = component.getId();
            switch (componentId) {
                case ResourceTable.Id_keepaccounts_save: {
                    //保存数据
                    try {
                        saveData();
                    } catch (DataAbilityRemoteException e) {
                        e.printStackTrace();
                    }

                }
                break;
                case ResourceTable.Id_goback_btn: {
                    //回退
                    terminate();//结束当前的abilityslice
                }
                break;
                case ResourceTable.Id_class_text: {
                    //弹出收支分类，选择分类
                    showPickAccountsTypeClass(KeepAccountsAbilitySlice.this);
                }
                break;
                case ResourceTable.Id_date_text: {
                    //弹出日期dialog，选择日期
                    showPickDateConfirmTips(KeepAccountsAbilitySlice.this);

                }
                break;
                case ResourceTable.Id_date_time_text: {
                    //弹出时间dialog，选择时间
                    showPickTimeConfirmTips(KeepAccountsAbilitySlice.this);
                }
                break;

            }

        }
    };

    //保存当前数据
    private void saveData() throws DataAbilityRemoteException {
        //记账页面的插入数据的非法检测
        Account account = new Account();
        String money = moneyTextfield.getText();
        if (money == null || "".equals(money)) {
            MyToast.showMyToast(this, "金额输入为空");
            return;
        } else if (!MyUtil.isMoneyNumber(money)) {
            MyToast.showMyToast(this, "金额输入不合法");
            return;
        } else {
            account.setAmoney(Double.valueOf(moneyTextfield.getText()));
        }
        //支出收入分类选中，分类数据数据
        if (item == null) {
            MyToast.showMyToast(this, "请选择分类");
            return;
        }
        account.setUid(Integer.valueOf(DataBaseUtil.GetValue(this, "uid")));
        account.setCid(item.getCid());

        //日期数据
        if ("".equals(dateText.getText()) || dateText.getText() == null) {
            MyToast.showMyToast(this, "日期不能为空！");
            return;
        } else if ("".equals(dateTimeText.getText()) || dateTimeText.getText() == null) {
            MyToast.showMyToast(this, "时间不能为空！");
            return;
        }
        String actime = "";

        // 日期拼接，缺失补零
        DecimalFormat Dformat = new DecimalFormat("0000");
        actime += Dformat.format(dateYear) + "-";
        Dformat = new DecimalFormat("00");
        actime += Dformat.format(dateMonth) + "-";
        actime += Dformat.format(dateDay) + " ";

        actime += Dformat.format(hours) + ":";

        actime += Dformat.format(mimute) + ":";

        actime += Dformat.format(second);

        HiLog.info(LABEL, "格式后字符串 " + actime);

        //备注
        account.setAremark(remarkText.getText());

        //设置记账时间
        account.setArtime(actime);
        //账单建立时间
        account.setActime(DateUtils.getStrTimeFromDateTime(new Date()));

        int i = AccountDBUtil.insertAccount(this, account);
        if (i > 0) {
            MyToast.showMyToast(this, "本地账单数据保存成功");
            createRemoteAccountData(MyUtil.createAccount, account);
        } else {
            MyToast.showMyToast(this, "账单数据保存失败，返回");
        }

    }


    private void createRemoteAccountData(String url, Object sendJsonObject) {
        getGlobalTaskDispatcher(TaskPriority.DEFAULT).asyncDispatch(() -> {
            ResultVo resultVo;
            String getRequestjson = null;
            Gson gson = new Gson();
            String sendjson = gson.toJson(sendJsonObject);
            //转化为json
            try {
                getRequestjson = HttpRequestUtil.sendPostRequestByOkHttp(url, sendjson);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (getRequestjson == null || getRequestjson.contains("not found")) {
                HiLog.info(LABEL, "无法连接到网络！");
                //刷新页面上的数据，同样有一个坑，onChange方法实质上，在一个子线程里执行
                getUITaskDispatcher().asyncDispatch(() -> {
                            //在这里执行页面ui组件的显示刷新
                            MyToast.showMyToast(this, "无法连接到网络");
                        }
                );
                return;
            } else {
                try {
                    resultVo = gson.fromJson(getRequestjson, ResultVo.class);
                } catch (Exception e) {
                    getUITaskDispatcher().asyncDispatch(() -> {
                        MyToast.showMyToast(this, "gson解析返回对象失败，请确定服务器是否开启");
                    });
                    HiLog.error(LABEL, "有网络但是连接不到服务器时返回数据为：" + getRequestjson);
                    return;
                }

                if (resultVo == null) {//返回对象进行解析
                    HiLog.info(LABEL, "返回对象为空！");
                    //刷新页面上的数据，同样有一个坑，onChange方法实质上，在一个子线程里执行
                    getUITaskDispatcher().asyncDispatch(() -> {
                        //在这里执行页面ui组件的显示刷新
                        MyToast.showMyToast(this, "返回为空,数据丢失！");
                    });
                    return;
                } else {
                    getUITaskDispatcher().asyncDispatch(() -> {
                        MyToast.showMyToast(this, "状态码" + resultVo.getCode() + " " + resultVo.getMsg());
                        if (resultVo.getCode() == 200) {
                            //在这里执行页面ui组件的显示刷新
                            HiLog.info(LABEL, "本地数据库创建成功！");
                            Intent resultIntent = new Intent();
                            setResult(resultIntent);
                            //   关闭当前Ability
                            terminateAbility();
                        }
                    });
                }
            }
        });

    }

    private void showPickAccountsTypeClass(AbilityContext context) {

        Component parse = LayoutScatter.getInstance(this).parse(ResourceTable.Layout_dialog_accountstype_select, null, false);
        ListContainer accountTypelistContainer = (ListContainer) parse.findComponentById(ResourceTable.Id_accountType_listContainer);

        //创建显示气窗
        CommonDialog dialog = new CommonDialog(this);
        dialog.setOffset(0, 10);
        dialog.setContentCustomComponent(parse);
        dialog.setSize(MATCH_CONTENT, MATCH_CONTENT);
        //取消按钮
        Button cancel = (Button) parse.findComponentById(ResourceTable.Id_cancel);

        if (accountsType == 0) {
            //装载数据,不能合并写，后面需要逆转换
            classifyProvider = new ClassifyProvider(classifies_expenditure, this);
            accountTypelistContainer.setItemProvider(classifyProvider);
        } else if (accountsType == 1) {

            //装载数据
            classifyProvider = new ClassifyProvider(classifies_income, this);
            accountTypelistContainer.setItemProvider(classifyProvider);
        } else if (accountsType == 2) {
            //装载数据
            classifyProvider = new ClassifyProvider(classifies_property, this);
            accountTypelistContainer.setItemProvider(classifyProvider);
        }

        cancel.setClickedListener(c -> {
            dialog.hide();
            MyToast.showMyToast(this, "已取消");

        });
        dialog.show();
        accountTypelistContainer.setItemSelectedListener(new ListContainer.ItemSelectedListener() {
            @Override
            public void onItemSelected(ListContainer listContainer, Component component, int i, long l) {
                component.setClickedListener(component1 -> {
                });
                item = (Classify) classifyProvider.getItem(i);
                MyToast.showMyToast(getContext(), "你选择了 " + item.getCname());
                HiLog.info(LABEL, "选择项对象信息" + item.toString());
                classText.setText(item.getCname());
                dialog.destroy();
            }
        });


    }

    private void clickOk(IDialog iDialog, int i) {
        iDialog.destroy();
        MyToast.showMyToast(this, "已确定");
    }

    private void clickCancel(IDialog iDialog, int i) {
        iDialog.destroy();
        MyToast.showMyToast(this, "已取消");

    }

    @Override
    public void onActive() {
        super.onActive();
    }

    //弹出日期dialog，选择日期
    public void showPickDateConfirmTips(AbilityContext context) {
        CommonDialog commonDialog = new CommonDialog(context);
        Component parse = LayoutScatter.getInstance(context)
                .parse(ResourceTable.Layout_dialog_date_layout_confirm, null, false);
        Text selectedDateText = (Text) findComponentById(ResourceTable.Id_date_text);
        DatePicker datePicker = (DatePicker) parse.findComponentById(ResourceTable.Id_date_pick);
        //取消按钮
        Button cancel = (Button) parse.findComponentById(ResourceTable.Id_cancel);
        //确定按钮
        Button ok = (Button) parse.findComponentById(ResourceTable.Id_ok);
        cancel.setClickedListener(c -> {
            commonDialog.destroy();
            MyToast.showMyToast(this, "已取消");

        });
        ok.setClickedListener(c -> {
            dateYear = datePicker.getYear();
            dateMonth = datePicker.getMonth();
            dateDay = datePicker.getDayOfMonth();
            selectedDateText.setText(DateUtils.getChineseFormatFromPicker(dateYear, dateMonth, dateDay));
            commonDialog.remove();
        });


        commonDialog.setOffset(0, 10);
        commonDialog.setSize(MATCH_CONTENT, MATCH_CONTENT);
        commonDialog.setAlignment(LayoutAlignment.CENTER);
        commonDialog.setTransparent(true);
        commonDialog.setCornerRadius(25);
        commonDialog.setContentCustomComponent(parse);
        commonDialog.show();
    }

    //弹出时间dialog，选择时间
    public void showPickTimeConfirmTips(AbilityContext context) {
        CommonDialog commonDialog = new CommonDialog(context);
        Component parse = LayoutScatter.getInstance(context)
                .parse(ResourceTable.Layout_dialog_time_layout_confirm, null, false);
        Text selectedTimeText = (Text) findComponentById(ResourceTable.Id_date_time_text);
        TimePicker timePicker = (TimePicker) parse.findComponentById(ResourceTable.Id_time_pick);
        //取消按钮
        Button cancel = (Button) parse.findComponentById(ResourceTable.Id_cancel);
        //确定按钮
        Button ok = (Button) parse.findComponentById(ResourceTable.Id_ok);
        cancel.setClickedListener(c -> {
            commonDialog.destroy();
            MyToast.showMyToast(this, "已取消");

        });
        ok.setClickedListener(c -> {
            hours = timePicker.getHour();
            mimute = timePicker.getMinute();
            second = timePicker.getSecond();
            selectedTimeText.setText(hours + ":" + mimute + ":" + second);
            commonDialog.remove();
        });
        commonDialog.setOffset(0, 10);
        commonDialog.setSize(MATCH_CONTENT, MATCH_CONTENT);
        commonDialog.setAlignment(LayoutAlignment.CENTER);
        commonDialog.setTransparent(true);
        commonDialog.setCornerRadius(25);
        commonDialog.setContentCustomComponent(parse);
        commonDialog.show();
    }


    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    //单选框选择变化时监听
    @Override
    public void onCheckedChanged(RadioContainer radioContainer, int i) {
        //选择第几个按钮
        accountsType = i;
        reloadColorData();
        if (accountsType == 0) {
            MyToast.showMyToast(this, "你选择了支出");
        } else if (accountsType == 1) {
            MyToast.showMyToast(this, "你选择了收入");
        } else if (accountsType == 2) {
            MyToast.showMyToast(this, "你选择了资产");
        }


    }

    private void getInputFromTextTextField(AbilityContext context, String Title, String hint, Component component) {
        getUITaskDispatcher().asyncDispatch(() -> {//ui刷新线程显示
            Text inputText = remarkText;
            //布局加载
            Component parse = LayoutScatter.getInstance(this).parse(ResourceTable.Layout_dialog_remark_layout_input, null, false);
            //标题
            Text title = (Text) parse.findComponentById(ResourceTable.Id_title);//创建显示气窗
            //输入框
            TextField textField = (TextField) parse.findComponentById(ResourceTable.Id_TextField);
            //设置要渲染的输入框数据
            title.setText(Title);
            textField.setHint(hint);
            //创建一个气窗
            CommonDialog dialog = new CommonDialog(this);
            //设置位置
            dialog.setOffset(0, 10);
            dialog.setContentCustomComponent(parse);
            dialog.setSize(MATCH_CONTENT, MATCH_CONTENT);
            //取消按钮
            Button cancel = (Button) parse.findComponentById(ResourceTable.Id_cancel);
            //确定按钮
            Button ok = (Button) parse.findComponentById(ResourceTable.Id_ok);

            textField.setText(inputText.getText());

            dialog.show();
            cancel.setClickedListener(c -> {
                dialog.destroy();
                MyToast.showMyToast(this, "已取消");

            });
            ok.setClickedListener(c -> {//按下确定按钮

                String strTextField = textField.getText();//得到输入框的值
                //如果原的值和输入框的值不一样，就取新的值
                if (!inputText.getText().equals(strTextField)) {
                    inputText.setText(strTextField);
                }
                dialog.hide();

            });
        });
    }


}
